import os
import json
import shutil
import zipfile
from collections import OrderedDict


class Build:

    @classmethod
    def to_exe(cls):
        cmd = '''C:\\Python310\\Scripts\\pyinstaller.exe -F -w -i Resource\\app.ico SystemController.py\
         --hidden-import pandas --hidden-import matplotlib'''
        os.system(cmd)

        for file in ['SystemController.exe', 'SystemController.spec']:
            if os.path.isfile(file):
                os.remove(file)

        if os.path.isfile('dist\\SystemController.exe'):
            shutil.move('dist\\SystemController.exe', '.\\')

        for path in ['build', 'dist', '__pycache__']:
            if os.path.isdir(path):
                shutil.rmtree(path)


class Pack:

    @classmethod
    def version(cls):
        with open('version') as f:
            return f.readline().strip()

    @classmethod
    def clear(cls):
        with open('.\\Interface\\settings.json', 'r', encoding='UTF-8') as f:
            data = json.load(f, object_pairs_hook=OrderedDict)
        data['Settings']['preference_ip'] = []
        data['Settings']['tool_version'] = cls.version()
        with open('.\\Interface\\settings.json', 'w', encoding='UTF-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=4)

    @classmethod
    def zip_dir(cls, dirname, zipname):
        filelist = []
        for root, dirs, files in os.walk(dirname):
            for name in files:
                filelist.append(os.path.join(root, name))
        zf = zipfile.ZipFile(zipname, "w", zipfile.zlib.DEFLATED)
        for tar in filelist:
            arcname = tar[len(dirname):]
            zf.write(tar, arcname)
        zf.close()

    @classmethod
    def pack(cls):
        if os.path.isdir('SystemController'):
            shutil.rmtree('SystemController')
        else:
            os.mkdir('SystemController')
        shutil.copytree('Interface', '.\\SystemController\\Interface')
        shutil.copytree('Resource', '.\\SystemController\\Resource')
        shutil.copytree('Docs', '.\\SystemController\\Docs')
        shutil.move('SystemController.exe', '.\\SystemController\\')
        shutil.copy('LICENSE', '.\\SystemController\\')

        cls.zip_dir('SystemController', 'SystemController-v%s.zip' % cls.version())

        if os.path.isdir('SystemController'):
            shutil.rmtree('SystemController')


def main():
    Build.to_exe()
    Pack.clear()
    Pack.pack()


if __name__ == '__main__':
    main()
